from flask import Blueprint
from model.company import Company
import requests
from utils.securtiy import *
from utils.work_db import get_session
from config import *
from service.user_service import UserService
from service.company_service import CompanyService
from service.job_servie import JobService
from service.user_deliver_service import UserDeliverStatusService
from model.user import *
from model.user_message import UserMessage
from model.job import Job
from utils.tools import format_date, format_datetime
import datetime
import uuid
from config import UPLOAD_DIR
from utils.work_log import get_logger
import os.path

api = Blueprint('company_api', __name__, url_prefix='/api/v1/company')

log = get_logger(__name__)


@api.route('/save', methods=['POST'])
@login_required
def save(**kwargs):
    """
    填写公司信息
    :param kwargs:
    :return:
    """
    user_id = get_user_id()
    params = request.json

    if not params["name"]:
        return json_response(None, msg='公司名称不能为空!', code=-1)
    if not params["address"]:
        return json_response(None, msg='公司地址不能为空!', code=-1)
    if not params["tel"]:
        return json_response(None, msg='联系电话不能为空', code=-1)

    uu_id = uuid.uuid1()
    session = get_session()
    company = Company()
    company.c_uuid = str(uu_id)
    company.name = str(params["name"])
    company.audit_status = 1
    company.create_userid = user_id
    company_service = CompanyService(session)
    user_service = UserService(session)
    data = dict(params)
    for k, v in data.items():
        setattr(company, k, v)
    # 认证
    if company.credentials_url:
        company.certification = 1
    company_service.merge(company)
    session.commit()

    # 绑定人员与企业之间关系
    q_company = company_service.get_by_uuid(str(uu_id))
    user = user_service.get_by_id(user_id)
    if not user.company_id:
        user = User()
        user.user_id = user_id
        user.company_id = q_company.company_id
        session.merge(user)
        session.commit()
    result = {
        "companyId": q_company.company_id,
        "certification": q_company.certification if q_company.certification else '',

    }
    return json_response(data=result, msg='操作成功', code=1)


@api.route('/get/<cid>', methods=['GET'])
@login_required
def get(cid, **kwargs):
    """
    获得公司详情
    :param cid:
    :param kwargs:
    :return:
    """
    session = get_session()
    company_service = CompanyService(session)
    company = company_service.get_by_company_id_detail(cid)
    curl = company.get("credentials_url") if company.get("credentials_url") else ''
    if curl:
        company["credentials_url"] = curl
    else:
        company["credentials_url"] = ''
    session.close()
    if company:
        return json_response(company, msg='')
    else:
        return json_response(None, msg='信息不存在', code=-1)


@api.route('/upload_quality', methods=['POST'])
@login_required
def upload_quality(**kwargs):
    """
    上传资质
    :param kwargs:
    :return:
    """
    quality_dir = UPLOAD_DIR + "/quality"
    if not os.path.exists(quality_dir):
        os.makedirs(quality_dir)
    file = request.files['file']
    ext = file.filename.rsplit('.', 1)[1]
    file_name = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + "." + ext
    simple_name = file_name
    file_name = os.path.join(quality_dir, file_name)
    file.save(file_name)
    return json_response(simple_name, msg='资质上传成功')


@api.route('/save_job', methods=['POST'])
@login_required
def save_job(**kwargs):
    """
    发布工作
    :param kwargs:
    :return:
    """
    user_id = get_user_id()
    uu_id = uuid.uuid1()
    params = request.json
    if not params["job_name"]:
        return json_response(None, msg='职位名称不能为空!', code=-1)
    job = Job()
    job.job_status = 1
    job.j_uuid = str(uu_id)
    job.create_userid = user_id
    data = dict(params)
    for k, v in data.items():
        setattr(job, k, v)
    session = get_session()
    user_service = UserService(session)
    j_service = JobService(session)
    user = user_service.get_by_id(user_id)
    if not user.company_id:
        return json_response(None, msg='请先进行公司认证，才可发表职位!', code=-1)
    job.company_id = user.company_id
    j_service.merge(job)
    session.commit()

    if not job.job_id:
        q_job = j_service.get_uuid(cuuid=str(uu_id))
        message = UserMessage()
        # 发布人
        message.user_id = user_id
        message.job_id = q_job.job_id
        message.message_type = 3
        message.content = '恭喜您,您发布的职位[{}]已审核通过,可以进行招募啦!!'.format(job.job_name)
        message.message_date = format_date(datetime.datetime.now())
        message.company_id = user.company_id
        message.create_userid = user_id
        session.add(message)
        session.commit()
    return json_response('', msg='操作成功', code=1)


@api.route('/get_job/<job_id>', methods=['GET'])
@login_required
def get_job(job_id, **kwargs):
    """
    获得具体工作详情
    :param job_id:
    :param kwargs:
    :return:
    """
    session = get_session()
    service = JobService(session)
    job = service.get_job_detail(job_id=job_id)
    return json_response(data=job, msg='', code=1)


@api.route('/get_jobs', methods=['POST'])
@login_required
def get_jobs(**kwargs):
    """
    获得本公司发表的职位
    :param kwargs:
    :return:
    """
    params = request.json
    user_id = get_user_id()
    session = get_session()
    user_service = UserService(session)
    user = user_service.get_by_id(user_id)
    service = JobService(session)
    job_list = service.get_job_by_company_id(company_id=user.company_id,
                                             kwargs=params)
    return json_response(data=job_list, msg='', code=1)


@api.route('/get_deliver_resume', methods=['POST'])
@login_required
def get_deliver_resume(**kwargs):
    """
    获得投递到本公司的简历
    :param kwargs:
    :return:
    """
    # params = request.json
    user_id = get_user_id()
    session = get_session()
    user_service = UserService(session)
    user = user_service.get_by_id(user_id)
    service = UserDeliverStatusService(session)
    # 职位下挂载投递信息
    resume_list = service.get_deliver_resume(company_id=user.company_id,
                                             **kwargs)
    return json_response(data=resume_list, msg='', code=1)


@api.route('/get_deliver_resume_fail/<job_id>', methods=['GET'])
@login_required
def get_deliver_resume_fail(job_id, **kwargs):
    """
    根据工作id获得本次未通过的招聘者信息
    :param job_id:
    :param kwargs:
    :return:
    """
    session = get_session()
    service = UserDeliverStatusService(session)
    resume_list = service.get_deliver_resume_fail(job_id=job_id,
                                                  **kwargs)
    return json_response(data=resume_list, msg='', code=1)


@api.route('/set_read/<deliver_id>', methods=['GET'])
@login_required
def set_read_count(deliver_id):
    """
    查看人员信息时候，设置投递查看次数
    :param deliver_id:
    :return:
    """
    session = get_session()
    d_service = UserDeliverStatusService(session)
    deliver = d_service.get(deliver_id=deliver_id)
    read_count = deliver.read_count
    if not read_count:
        read_count = 0
    read_count = (read_count + 1)
    deliver.read_count = read_count
    session.merge(deliver)
    session.commit()
    session.close()
    return json_response(data='', msg='操作成功', code=1)


@api.route('/get_user/<userid>', methods=['GET'])
@login_required
def get_user(userid, **kwargs):
    """
    求职者详细信息
    :param userid:
    :param kwargs:
    :return:
    """
    session = get_session()
    user_service = UserService(session)
    q_user = user_service.get_user_and_resume_by_id(userid)
    data = q_user
    data["openid"] = ''
    if q_user:
        return json_response(q_user, msg='')
    else:
        return json_response(None, msg='信息不存在', code=-1)


@api.route('/audit_deliver', methods=['POST'])
@login_required
def audit_deliver(**kwargs):
    """
    审核投递
    :param kwargs:
    :return:
    """
    params = request.json
    # 投递记录id
    deliver_id = params.get("deliver_id")
    # 操作人id
    user_id = get_user_id()
    session = get_session()
    service = UserDeliverStatusService(session)
    deliver = service.get(deliver_id=deliver_id)
    # 投递人id
    deliver_user_id = deliver.user_id
    deliver.audit_status = params.get("audit_status")
    deliver.audit_userid = user_id
    deliver.audit_time = format_datetime(datetime.datetime.now())
    session.merge(deliver)
    # 消息
    if int(params.get("audit_status")) == 1:
        message = UserMessage()
        # 投递人
        message.user_id = deliver_user_id
        message.job_id = deliver.job_id
        # 投递简历，回执
        message.message_type = 2
        message.content = '您的投递的简历,已经通过!'
        message.message_date = format_date(datetime.datetime.now())
        message.company_id = deliver.company_id
        message.create_userid = user_id
        session.add(message)
    session.commit()
    session.close()
    return json_response(data='', msg='操作成功', code=1)


# 审核状态(0:待处理 1:通过 2:暂停)
""""
{
 "job_id":1
 "status":1/2
}
"""


@api.route('/audit_job', methods=['POST'])
@login_required
def audit_job(**kwargs):
    """
    审核工作,暂停工作招聘(下架工作)
    :param kwargs:
    :return:
    """
    params = request.json
    job_id = params.get("job_id")
    status = params.get("status")
    user_id = get_user_id()
    session = get_session()
    service = JobService(session)
    job = Job()
    job.job_id = job_id
    job.audit_userid = user_id
    job.job_status = int(status)
    service.merge(job)
    session.commit()
    session.close()
    return json_response(data='', msg='操作成功', code=1)


@api.route('/mine', methods=['POST', 'GET'])
@login_required
def mine(**kwargs):
    """
    我的
    发布过的职位，通过的人数
    :param kwargs:
    :return:
    """
    user_id = get_user_id()
    session = get_session()
    user_service = UserService(session)
    data = user_service.get_detail(user_id=user_id)
    return json_response(data=data, msg='', code=1)


@api.route('/login', methods=['POST'])
def login():
    """
    企业用户登陆
    :return:
    """
    session = get_session()
    params = request.json
    if params and params.get("code"):
        code = params["code"]
        wx_param = dict(WX_COMPANY_CONFIG)
        wx_param["js_code"] = code
        send_r = requests.get(wx_session_url, params=wx_param, timeout=5)
        wx_result = send_r.json()
        if wx_result:
            wx_openid = wx_result["openid"]
            union_id = wx_result.get("unionid")
            wx_user = params["user"]
            q_user_service = UserService(session)
            q_user = q_user_service.get_by_openid(wx_openid, user_type=2)
            if q_user and q_user.openid:
                t_user = {"user_id": q_user.user_id,
                          "tel": q_user.tel,
                          "wx_openid": wx_openid}
                m_token = create_jwt(t_user)
                r_user = {"token": m_token,
                          "user_id": q_user.user_id,
                          "tel": q_user.tel}
                session.commit()
                if q_user.company_id:
                    r_user["company_id"] = q_user.company_id
                else:
                    # 未认证
                    r_user["company_id"] = -1
                return json_response(r_user, msg='登陆成功', code=1)
            else:
                user = User()
                user.openid = wx_openid
                if wx_user:
                    user.header_img = wx_user["avatarUrl"]
                    user.wx_nick_name = wx_user["nickName"]
                    user.gender = wx_user["gender"]
                    user.unionid = union_id
                    user.user_type = USER_TYPE_COMPANY
                    q_user_service.add_user(user)
                session.commit()
                q_user = q_user_service.get_by_openid(wx_openid, user_type=2)
                t_user = {"user_id": q_user.user_id,
                          "tel": q_user.tel,
                          "wx_openid": wx_openid}
                token = create_jwt(t_user)
                r_user = {"token": token,
                          "user_id": q_user.user_id,
                          "tel": q_user.tel}
                if q_user.company_id:
                    r_user["company_id"] = q_user.company_id
                else:
                    # 未认证
                    r_user["company_id"] = -1

                return json_response(r_user, msg='登陆成功', code=1)
        else:
            return json_response(None, msg='登陆错误!', code=-1)
    else:
        return json_response(None, msg='授权码code为空!', code=-1)
